var menuItem=new Array();//品牌

//初始化加载折线图和表格
$(document).ready(function () {
	siteId = $("#siteIds").val();
	brandId = $("#brandIds").val();
	type = $("#hdtype").val();
	if(siteId==""||brandId=="" ||type==""){
		var str = "<div class='em100 whitediv' id='zhanwushuju'><div class='em25'></div><div class='backyellow'>&nbsp;&nbsp;暂无数据！请选择场所</div></div>"
		$("#myForm .widthall .chartdiv").children("div[id!='zhanwushuju']").hide();
		$("#myForm .widthall .xiangxidiv").children("div[id!='zhanwushuju']").hide();
		$("#myForm .widthall .chartdiv").html(str);
		$("#myForm .widthall .xiangxidiv").html(str);
	}else{
		//趋势指标初始化
		getIndexOrder();
	}
})

function initSCIndexGroup(){
	
	var indexDay = dateindexPowerList[getTimeIndexList()];
	var selectZhibiao = "";
	for(var p in indexListOfGroup){
		var indexList = indexListOfGroup[p];
		for(var i = 0;i<indexList.length;i++){
			if(containstr(indexDay,indexList[i])){
				selectZhibiao = selectZhibiao +"<option value="+p+">"+arrayGroup[p]+"</option>";
				break;
			}
		}
	}
	$("#select_SCzhibiao").html(selectZhibiao);
}
function SCindexPower(){
	//获取后台返回的权限列表
	var option = $("#select_SCzhibiao").val()
	var name = indexListOfGroup[option];
	//设置权限把没有权限指标remove
	setSCIndex(name)
	//取页面中有权限的第一个指标
	var kk=$("#SCzhibiaotable>tbody>tr>td").first();
	if(kk!=null){
	var kk=(kk.attr("id").split("_"))[1];
    getSCinfo(parseInt(kk),"");
    }else{
    	alert("没有指标权限");
    }
}

//设置用户权限下面的指标个数
function setSCIndex(Str){
	var index=eval(Str);
	var indexDay = dateindexPowerList[getTimeIndexList()];
	indexDay = eval(indexDay);
	var name = new Array();
	for (var i=0; i<indexDay.length; i++) {
		if(containstr(index,indexDay[i])){
			name.push(indexDay[i])
		}
	};
	
	/**
	 * start如果是销售数据、会员数据修改下拉顺序
	 */
	 var newName = new Array();
	 var Select_big_type = $("#select_SCzhibiao").val();
	 if(Select_big_type == 0){//视频数据
		 var xiaoshouIndex = getIndexOrderAjax[0];
		 for (var i = 0; i < xiaoshouIndex.length; i++) {
		 	if (containstr(name, xiaoshouIndex[i])) {
		 		newName.push(xiaoshouIndex[i]);
		 		name.remove(xiaoshouIndex[i]);
		 	}
		 }
		 for (var j = 0; j < name.length; i++) {
		 	newName.push(name[i]);
			name.remove(name[i]);
		 }
	 	name = newName;
	 }
	 if(Select_big_type == 1){//销售数据
		 var xiaoshouIndex = getIndexOrderAjax[1];
		 for (var i = 0; i < xiaoshouIndex.length; i++) {
		 	if (containstr(name, xiaoshouIndex[i])) {
		 		newName.push(xiaoshouIndex[i]);
		 		name.remove(xiaoshouIndex[i]);
		 	}
		 }
		 for (var j = 0; j < name.length; i++) {
		 	newName.push(name[i]);
			name.remove(name[i]);
		 }
	 	name = newName;
	 }
	 if(Select_big_type == 2){//wifi数据
		 var xiaoshouIndex = getIndexOrderAjax[2];
		 for (var i = 0; i < xiaoshouIndex.length; i++) {
		 	if (containstr(name, xiaoshouIndex[i])) {
		 		newName.push(xiaoshouIndex[i]);
		 		name.remove(xiaoshouIndex[i]);
		 	}
		 }
		 for (var j = 0; j < name.length; i++) {
		 	newName.push(name[i]);
			name.remove(name[i]);
		 }
	 	name = newName;
	 }
	 if(Select_big_type == 3){//销售数据
		 var xiaoshouIndex = getIndexOrderAjax[3];
		 for (var i = 0; i < xiaoshouIndex.length; i++) {
		 	if (containstr(name, xiaoshouIndex[i])) {
		 		newName.push(xiaoshouIndex[i]);
		 		name.remove(xiaoshouIndex[i]);
		 	}
		 }
		 for (var j = 0; j < name.length; i++) {
		 	newName.push(name[i]);
			name.remove(name[i]);
		 }
	 	name = newName;
	 }
	 if(Select_big_type == 4){//会员数据
		  var huiyuanIndex = getIndexOrderAjax[4];
		  for (var i = 0; i < huiyuanIndex.length; i++) {
		 	if (containstr(name, huiyuanIndex[i])) {
		 		newName.push(huiyuanIndex[i]);
		 		name.remove(huiyuanIndex[i]);
		 	}
		 }
		 for (var j = 0; j < name.length; i++) {
		 	newName.push(name[i]);
			name.remove(name[i]);
		 }
		 name = newName;
	 }
	 /**
	  * end如果是销售数据、会员数据修改下拉顺序
	  */
	
	var zhibiaotable = "";
	for (var i=0; i<name.length; i++) {
		var zhibiao = name[i];
		zhibiaotable = zhibiaotable +"<tr><td id='SCzhibiao_"+zhibiao+"' class='em35 lineh35' onclick='getSCinfo("+zhibiao+",this)'>"+array[zhibiao]+"</td></tr>"
	};
	$("#SCzhibiaotable").html(zhibiaotable);
}

function changeSCzhibiao(object){
	var option = $(object).val()
	var name = indexListOfGroup[option];
	setSCIndex(name,getTimeIndexList())
    var indexName =	$("#sandianType").val();
	var indexName = indexName.split(',');
	$("#SCzhibiao_"+indexName[0]).addClass("lxxzselected");
	$("#SCzhibiao_"+indexName[1]).addClass("lxxzselected");
	
}
var indexSandian = new Array();
function getSCinfo(type,Object){
	if(indexSandian.length == 0){
		indexSandian[0] = type;
		indexSandian[1] = type;
	}else{
		indexSandian[0] = indexSandian[1];
		indexSandian[1] = type;
	}
	$("#sandianType").val(indexSandian[0]+','+indexSandian[1]);
	
	$("#SCzhibiaotable td").each(function(){
		$(this).removeClass("lxxzselected");
	})
	
	for(var ind = 0;ind<indexSandian.length;ind++){
		$("#SCzhibiao_"+indexSandian[ind]).addClass("lxxzselected");
	}
	laodSC(indexSandian[0],indexSandian[1]);
}
function getGCData(Object){
	var sandianType = $("#sandianType").val();
	var sandianType = sandianType.split(',')
	var indexName1 =  getOrderField(sandianType[0]);
	var indexName2 =  getOrderField(sandianType[1]);
	var gc = "["
	for(var i =0;i<Object.length;i++){
		var ob = Object[i]
		var index = new Array();
		var indexData1 = getObjectVlue(ob,indexName1)==null||getObjectVlue(ob,indexName1)==""?0:getObjectVlue(ob,indexName1)
		var indexData2 = getObjectVlue(ob,indexName2)==null||getObjectVlue(ob,indexName2)==""?0:getObjectVlue(ob,indexName2)
		var index = "["+parseFloat(indexData1)+","+parseFloat(indexData2)+"]";
		gc = gc + index +",";
	}
	gc  = gc.substring(0,gc.length-1);
	gc = gc + "]";
	return gc
}

function laodSC(type,type1){
	
	var width = $("#shangchang").width();
	var height = $("#shangchang").height();
	titleOffens = width*7.6/100;
	dataZoomY = height*(1-19/100);
	toolboxX = width*77/100;
	var legendY = height*4.5/100;
	var toolboxY = height*0.5/100;
	var  titContext = "";
	var toolboxName ="";
	
	 //获取指标名称
     var indexname = array[parseInt(type)];
	  //获取指标单位
	 var zhibiaodanwei = arraydanwei[parseInt(type)];
	 
//	 var hdtype = $("#hdtype").val();
	  //获取指标名称
     var indexname1 = array[parseInt(type1)];
	  //获取指标单位
	 var zhibiaodanwei1 = arraydanwei[parseInt(type1)];
	 
	 var titContext = "数据说明：商场品牌表现"+"\n"
				+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"\n"
				+"场所名称："+siteIdForJituan+"\n"
				+"指标名称："+indexname1+"（"+zhibiaodanwei1+"）";
	 
	 var data = [];
     var xsis = [];
     var from = $('#startDate').val();
     var to = $('#endDate').val();
     var from2 = "";
     var to2 = "";
     var siteId= $("#siteIds").val();
	 var brandId= $("#brandIds").val();
     var span = $("#txtspan").val();
//     shijianCss(span);
    var myChart = echarts.init(document.getElementById("shangchang"));
   	$.ajax( {
   		type : "GET",
   		contentType:"application/json",
   		dataType : 'json',
   		url: "getScatterGraphData",
   		data: { from: from, to: to, type: type, span: span, brandId: brandId ,siteId:siteId},
   		async: true,
   		success : function(ret) {
			 var dataList = ret.result
			 var legendData = new Array();
			 var seriesData = "";
			 var maxvalue = 0;
			 for(var i=0;i<dataList.length;i++){
			 	var data = dataList[i];
			 	var serieData = getGCData(data.dataList);
				var arr = eval(serieData);
				for(var i1 = 0;i1 < arr.length;i1++){
					var arrtemp = arr[i1];
				 	var tempVale = arrtemp[1];
					if(tempVale > maxvalue){
						maxvalue = tempVale;
					}
				}
			 }
			 var sizeper = maxvalue/30;
			 for(var i=0;i<dataList.length;i++){
			 	var data = dataList[i];
			 	legendData.push(data.brandName);//[[161.2, 51.6], [167.5, 59.0]]
			 	var serieData = getGCData(data.dataList);
				seriesData = seriesData+  "{name:'"+data.brandName+"',type:'scatter',symbol: 'circle',symbolSize: function (value){return Math.round(value[1] / "+sizeper+");},data:"+serieData+" },"
			 }
			 seriesData.substring(0,seriesData.length-1);
			 seriesData = eval("["+seriesData+"]");
			 
			
			 option = {
			 	title : {
		   		      text: titContext,
		   		      y:'bottom',
		   		      x:titleOffens,
		   		      textStyle:{
		   		        fontSize: 12,
		   		        color: '#666',
						fontFamily:'微软雅黑, 兰亭细黑, 宋体',
		   		        fontWeight:'normal'
		   		    	}		
		   		    },
			 	tooltip: {
			 		trigger: 'axis',
			 		showDelay: 0,
			 		formatter: function(params){
			 			if (params.value.length > 1) {
			 				return params.seriesName + ' :<br/>' +
			 				params.value[1] +
			 				zhibiaodanwei1 +";"+
			 				params.value[0] +
			 				zhibiaodanwei;
			 			}
			 			else {
			 				return params.seriesName + ' :<br/>' +
			 				params.name +
			 				' : ' +
			 				params.value +
			 				zhibiaodanwei1;
			 			}
			 		},
			 		axisPointer: {
			 			show: true,
			 			type: 'cross',
			 			lineStyle: {
			 				type: 'dashed',
			 				width: 1
			 			}
			 		}
			 	},
			 	legend: {
			 		data: legendData,
					y:legendY
			 	},
			 	grid:{
		   				x:'7.6%',
		   				y:'11%',
		   				y2:'17%',
		   				borderWidth: gridBorderWidth,
						borderColor:'#EEE'
		   			},
			    toolbox: {
					show : true,
			        feature : {
			            mark : {show: true},
			            dataZoom : {show: true},
			            dataView : {show: true, readOnly: false},
			            restore : {show: true},
			            saveAsImage : {
							show: true,
							name: toolboxName 
						}
			        },
			        x:toolboxX,
					y:toolboxY
			    },
			 	xAxis: [{
					name:indexname+'('+zhibiaodanwei+')',
			 		type: 'value',
			 		scale: true,
			 		axisLabel:{
						formatter: function (value) {
		            		if(value > 10000){
		            			return (value/10000)+'万';
		            		}else{
		            			return value + '';
		            		}
						}
					},
			 	}],
			 	yAxis: [{
					name:indexname1+'('+zhibiaodanwei1+')',
			 		type: 'value',
			 		scale: true,
			 		axisLabel:{
						formatter: function (value) {
		            		if(value > 10000){
		            			return (value/10000)+'万';
		            		}else{
		            			return value + '';
		            		}
						}
					},
			 	}],
			 	series: seriesData
			 }
			//改变窗口大小使图标自适应窗口显示
		   			window.onresize = function () {
		   				myChart.resize();
		   			}
		   			//加载折线图
		   			myChart.setOption(option);
//					hideLoading();
				},
				error : function(mm, a, b, c, d, e) {
					hideLoading();
					alert("服务器好像开小差了，刷新一下试试吧！");
				}
	})
}


//时间段时间控件
$( function () {
	var endDate=new Date();//当前时间
	endDate=endDate.getFullYear()+"-"+(endDate.getMonth()+1)+"-"+endDate.getDate();
	var startDate=(new Date());
	startDate.setDate(startDate.getDate()-30);//前一个月时间
	startDate=startDate.getFullYear()+"-"+(startDate.getMonth()+1)+"-"+startDate.getDate();

    var dateObj = {
        theme: 'ta', // 日期选择器TA主题
        autoCommit: true, //自动提交，完成日期初始化，以及图表的展示拉取
        isTodayValid: true,
        startDate: startDate,
        endDate: endDate,
        needCompare: true,
        startCompareDate: '',
        endCompareDate: '',
        singleCompare: false,
        defaultText: ' 至 ',
        autoSubmit: false,
        shortOpr: false,
        target: 'datePicker',
        calendars: 2,
        inputTrigger: 'input_trigger',
        compareCheckboxId: false,
        success: function (obj) {
            if (($("#txtspan").val().split("_"))[1] == "0" || $("#needCompare").val() == "1")//处于如期选择框时
            {
                loadChart($("#hdtype").val());
            }
        }
    };
    new pickerDateRange("date", dateObj)
})

//加载折线图表取XY轴
function  getXY(timeType_table,dataList,type) {
	var xsisRe="";
	var dataRe="";


	for(var i=0;i<dataList.length;i++){
		xsisRe=xsisRe + dataList[i].datatime+",";
		if(type==1){ //客流量
  				dataRe=dataRe + dataList[i].innum+",";
		}else if(type==2){//銷售額
  				dataRe=dataRe + dataList[i].pos+",";
		}
	}
	xsisRe=xsisRe.substring(0,xsisRe.length-1);
	dataRe=dataRe.substring(0,dataRe.length-1);
	var result =new Array();
	result.push(xsisRe);
	result.push(dataRe);
	return result
}

var stadubiao ;
var endtubiao;
var siteIdstr;
var indexname;
var zhibiaodanwei;
var siteIdForJituan;
//加载折线图表
 function loadChart(type) {
 	 showLoading();
	//指标显示底色
	 zhibiaoCss(type);
	 //获取指标名称
     indexname = array[parseInt(type)];
	  //获取指标单位
	 zhibiaodanwei = arraydanwei[parseInt(type)];
	 var data = [];
     var xsis = [];
     var from = $('#startDate').val();
     var to = $('#endDate').val();
     var from2 = "";
     var to2 = "";
     var siteId= $("#siteIds").val();
	 var brandId= $("#brandIds").val();
     var tubiao = "tubiao1";
     var span = $("#txtspan").val();
     shijianCss(span);
     var myChart = echarts.init(document.getElementById(tubiao));
   	$.ajax( {
   		type : "GET",
   		contentType:"application/json",
   		dataType : 'json',
   		url: "getBrandAnalysis",
   		data: { from: from, to: to, type: type, span: span, brandId: brandId ,siteId:siteId},
   		async: true,
   		success : function(ret) {
			//下面表情的位置
   			var width = $("#tubiao1").width();
   			var height = $("#tubiao1").height();
			var titleOffens = "";
   			var dataZoomY = "";;
   			var toolboxX = "";
			titleOffens = width*7.6/100;
			dataZoomY = height*(1-19/100);
			toolboxX = width*80/100;
			var legendY = height*4.5/100;
			var toolboxY = height*0.5/100;
			//获取当前时间
			var date = new Date;
			var today =  timeFormat(date);
			//保存图片名称
			var toolboxName = $("#titles").val()+'-品牌趋势对比'+today;
			var xsisRe="";//X轴
   			var dataRe="";//数据线
   			var titName="";//标题
   			var legendData = new Array();
			indexNamefiled = getOrderField(type);
		
   			var  result = ret.result;//返回数据集
   			
			
			
   			var item ="";
			for(var i = 0 ;i<result.length;i++){
				var pramdata = result[i]
				var brandName= pramdata.brandName;
				var brandId= pramdata.brandId;
				var dataList= pramdata.dataList;
				var listDate= pramdata.listDate;
				//时间轴
				xsisRe = listDate;
				/**
	   			 * 横坐标只有一个值时显示为柱状图，柱状宽度最大为40
	   			 */
	   			var lineType = 'line';
	   			if(xsisRe.length ==1){
	   				lineType = 'bar';
	   			}else{
	   				lineType = 'line';
	   			}
				
				legendData.push(brandName);
				var data = new Array();
				for(var dl = 0;dl<dataList.length;dl++){
					data.push(((getObjectVlue(dataList[dl],indexNamefiled))==null?0:(getObjectVlue(dataList[dl],indexNamefiled))));
				}
				var barMaxWidthn = 40;
   				var markLinePrecision = 0;
				item =item+ "{name:'"+brandName+"',markLine: {precision:markLinePrecision, data: [{type: 'average',name: '平均值'}]},type:lineType,smooth: smoothType,barMaxWidth:barMaxWidthn,itemStyle:{ normal:{color:'#feab41'}},itemStyle:{normal:{label:{show:false,position:'top'}}},data:[" +data + "]}"+",";
							
			}
			stadubiao = xsisRe[0];
			endtubiao = xsisRe[xsisRe.length-1];
			if(stadubiao == endtubiao){
				endtubiao = null;
			}
			
			data = eval("["+item+"]");
			var brands ="";
			for (var i=0; i<legendData.length; i++) {
				brands = brands + legendData[i] + "&";
			};
			brands = brands.substring(0,brands.length-1);
			
			var siteIds = "";
			siteIdArr = siteId.split(",")
			for (var i=0; i<siteIdArr.length; i++) {
				if(siteIdArr[i]!=null&&siteIdArr[i]!=""){
					siteIds = siteIds + siteIdArr[i] + "&";
				}
			};
			siteIdstr = ret.siteIdstr;
			siteIdForJituan = ret.siteIdForJituan;
			var titContext="数据说明：品牌趋势对比	"+"\n"
					+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"\n"
					+"场所名称："+siteIdForJituan+"\n"
					+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
					
					
			var biaogeshuomingContext = "数据说明：品牌趋势对比"+"<br/>"
				+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"<br/>"
				+"场所名称："+siteIdForJituan+"<br/>"
				+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
			$("#biaogeshuoming").html(biaogeshuomingContext);
		var  option = {
			legend: {
        		data:legendData,
				y:legendY
    		},
   			title : {
   		      text: titContext,
   		      y:'bottom',
   		      x:titleOffens,
   		      textStyle:{
   		        fontSize: 12,
   		        color: '#666',
				fontFamily:'微软雅黑, 兰亭细黑, 宋体',
   		        fontWeight:'normal'
   		    	}		
   		    },
   		    dataZoom: {
   		        show: true,
   		        y:dataZoomY 
   		    },
   			 tooltip: {
	   				trigger: 'axis',
	   				backgroundColor: 'rgba(0,0,0,0.7)',
	   				position: function(p) {
	   					return [p[0] + 10, p[1] - 10];
	   				},
					formatter: function(params, ticket, callback){
						var returnstr = "";
						var time = params[0][1];
							returnstr = "<tr>"+time+"</tr>";
						for (var i=0; i<params.length; i++) {
							var a = params[i][0];
							var c = params[i][2];
							c = addKannma(c);
							if (c == '') {
								c = 0;
							}
							returnstr = returnstr +  "<tr><td>"+a+"："+"</td><td  style='text-align: right;'>"+c+"</td></tr>";
							
						};
						var table = "<table>"+returnstr+"</table>"
						return table;
					}
	   			},
   			grid:{
   				x:'7.6%',
   				y:'11%',
   				y2:'27%',
   				borderWidth: gridBorderWidth,
				borderColor:'#EEE'
   			},
		    toolbox: {
		        show : true,
		        feature : {
		            mark : {show: true},
		            magicType : {show: true, type: ['line', 'bar']},
		            restore : {show: true},
		            saveAsImage : {
						show: true,
						name: toolboxName 
					}
		        },
		        x:toolboxX,
				 y:toolboxY
		    },
		    calculable : true,
		    xAxis : [
		        {
		        	name : '日',
		        	boundaryGap: true,//两端空白策略
		        	allowDecimals :true,//使用小数
		            type : 'category',
		            splitLine: {show: xAxisSplitLine,
					lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
		            splitArea:{
						show:xAxissplitArea,
						areaStyle:{
								color: [
						        'rgba(250,250,250,0.1)',
						        'rgba(200,200,200,0.1)']
							}
					},
		            data : xsisRe,
		            axisTick:{
						show:true,
						interval:0
					}
		        }
		    ],
		    yAxis : [
		        {
					axisLabel:{
						formatter: function (value) {
		            		if(value > 10000){
		            			return (value/10000)+'万';
		            		}else{
		            			return value + '';
		            		}
						}
					},
		        	splitLine: {
						show: yAxisSplitLine,
						lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
		        	splitArea:{
						show:yAxissplitArea,
						areaStyle:{
							color: [
					        'rgba(250,250,250,0.1)',
					        'rgba(200,200,200,0.1)']
						}
					},
		        	name : indexname+'('+zhibiaodanwei+')',
		            type : 'value'
		        }
		    ],
		    series : data
		};
   			//改变窗口大小使图标自适应窗口显示
   			window.onresize = function () {
   				myChart.resize();
   			}
   			//加载折线图
   			myChart.setOption(option);
			hideLoading();
   			//加载表格
   			loadTable1(ret.loadTable);
			initSCIndexGroup();
			SCindexPower();
   			//获取排行榜数据
			loadPaiHang(siteId,type);
			
//   			loadSelectedRanking(type);
//   			loadPaiHang(type);
			//商场指标初始化
			
   		},
		error : function(mm, a, b, c, d, e) {
				hideLoading();
				alert("服务器好像开小差了，刷新一下试试吧！");
			}
   	})
}

//品牌排序
function paihangpaixu1(){
	var src=$("#phpaixu1").attr("src");
	if(src.indexOf("asc.png")>0){
		$("#phpaixu1").attr("src","images/desc.png");
		$("#orderBy1").val("1");
	}else{
		$("#phpaixu1").attr("src","images/asc.png");
		$("#orderBy1").val("0");
	}
	parseDate(SelectPaihang,"1",myChart1);
}
//全部品牌排序
function paihangpaixu2(){
	var src=$("#phpaixu2").attr("src");
	if(src.indexOf("asc.png")>0){
		$("#phpaixu2").attr("src","images/desc.png");
		$("#orderBy2").val("1");
	}else{
		$("#phpaixu2").attr("src","images/asc.png");
		$("#orderBy2").val("0");
	}
	parseDate(paihangList,"2",myChart2);
}

var paihangList = new Array();
var SelectPaihang = new Array();

//获取选中的指标的排行
function getSelectPaihang(){
	var retArr = new Array();
	var brandId= $("#brandIds").val();
	brandIds = brandId.split(",");
    for(var i =0;i<paihangList.length;i++){
		var paihang = paihangList[i];
		if(containsStr(brandIds,paihang.brandId)){
			retArr.push(paihang);
		}
	}
	 return retArr;
}
/**
 * 将对象中特定字段转为doubel
 * @param {Object} data
 */
function getdoubelDate(data){
	
	var indexNames = new Array();
	indexNames.push("innum");
	indexNames.push("jkl");
	indexNames.push("posStaff");
	indexNames.push("pos");
	indexNames.push("rateBags");
	indexNames.push("posInnum");
	indexNames.push("posArea");
	indexNames.push("posnum");
	indexNames.push("retentionavg");
	indexNames.push("customerNum");
	indexNames.push("newCustomerNum");
	indexNames.push("oldCustomer");
	indexNames.push("newCustomerPro");
	indexNames.push("oldCustomerPro");
	indexNames.push("returnStoreRates");
	indexNames.push("memNum");
	indexNames.push("activeUserNum");
	indexNames.push("silenceUserNum");
	indexNames.push("interNum");
	indexNames.push("newInterNum");
	indexNames.push("interAvgDuration");
	
	var dataArr = new Array();
	for(var i = 0;i<data.length;i++){
		dataArr.push(changeStringTodouble(data[i],indexNames));
	}
	return dataArr
}
var myChart1;
var myChart2;

//加载数据
function loadPaiHang(siteId,type) {
	 //获取指标名称
     var indexname = array[parseInt(type)];
	  //获取指标单位
	 var zhibiaodanwei = arraydanwei[parseInt(type)];
	 var data = [];
     var xsis = [];
     var from = $('#startDate').val();
     var to = $('#endDate').val();
     var from2 = "";
     var to2 = "";
     var siteId= $("#siteIds").val();
     var span = $("#txtspan").val();
     shijianCss(span);
	 myChart1 = echarts.init(document.getElementById("divpaiming1"));
	 myChart2 = echarts.init(document.getElementById("divpaiming2"));
	 myChart1.showLoading({
    	text: '正在努力的读取数据中...',    //loading话术
    	effect : 'bar',
		});
		myChart2.showLoading({
    	text: '正在努力的读取数据中...',    //loading话术
    	effect : 'bar',
		});
	 
   	$.ajax( {
   		type : "GET",
   		contentType:"application/json",
   		dataType : 'json',
   		url: "getPaihangGraphData",
   		data: { from: from, to: to, type: type, span: span,siteId:siteId},
   		async: true,
   		success: function(ret){
			var result = ret.dataList;
			paihangList = eval(result);
			paihangList = getdoubelDate(paihangList);
			SelectPaihang = getSelectPaihang();
			SelectPaihang = getdoubelDate(SelectPaihang);
			if(paihangList.length == 0){
				var str = "<div class='em100 whitediv' id='zhanwushuju'><div class='em25'></div><div class='backyellow'>&nbsp;&nbsp;没有品牌</div></div>"
				$("#divph .whitediv").children().hide();
				$("#divph .whitediv").html(str);
			}else{
				parseDate(SelectPaihang,"1",myChart1);
				parseDate(paihangList,"2",myChart2);
			}
			myChart1.hideLoading();
			myChart2.hideLoading();
			
		},
		error : function(mm, a, b, c, d, e) {
				myChart1.hideLoading();
				myChart2.hideLoading();
				alert("服务器好像开小差了，刷新一下试试吧！");
			}
	})
}

function orderByType(type,data,order){
	var order = order;//0降序；1升序
	var index ="";
	var data = data;
	if(type != ""){
		index = (type.split(","))[0];
	}
	indexName = getOrderField(index);
	if(order =="1"){//升序
		data.sort(compare1(indexName,"brandName"));
		
	}else{//降序
		data.sort(compare1(indexName,"brandName"));
		data.reverse();
	}
	return data;
}

/**
 * 定义一个比较器 
 * 使用方法
 * data.sort(compare1("name")); 
 * alert(data[0].name);//jiang
 * @param propertyName
 * @return
 */
function compare1(propertyName,name) {
	return function (object1, object2) {
		var value1 = object1[propertyName];
		var value2 = object2[propertyName];
		var name1 = object1[name];
		var name2 = object2[name];
		
		if (value2 < value1) {
			return -1;
		} 
		else if (value2 > value1) {
			return 1;
		}else if(value2 == value1){
			if (name2 < name1) {
			return -1;
			} 
			else if (name2 > name1) {
				return 1;
			}else {
				return 0;
			}
		}else {
			return 0;
		}
	}
}


function parseDate(data1,modolType,myChart){
	var orderBy = $("#orderBy"+modolType).val();
	var rankingIndex = $("#hdtype").val();
	var parseDate = orderByType(rankingIndex,data1,orderBy);
	/*
	指标说明选的指标的名称
	
	var indexAndIndexName = "";
	for (var i=0; i<rankingIndex.length ; i++) {
		var index = rankingIndex[i];
		indexAndIndexName = indexAndIndexName + array[parseInt(index)]+"("+arraydanwei[parseInt(index)]+")"+"&"
	}
	indexAndIndexName = indexAndIndexName.substring(0,indexAndIndexName.length-1);
	var titNamepaihang = "";
	
		 titNamepaihang = "数据说明："+getsiteTypeChinaName(siteType)+timeModleName+"指标排行"+"<br/>"
					+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"<br/>"
					+"场所名称："+siteN+"<br/>"
					+"指标名称："+indexAndIndexName;
	*/
	if(modolType=="1"){
		var biaogeshuomingContext = "数据说明：品牌排行"+"<br/>"
				+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"<br/>"
				+"场所名称："+siteIdForJituan+"<br/>"
				+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
			$("#paihangshuoming").html(biaogeshuomingContext);
	}else{
		var biaogeshuomingContext = "数据说明：全部品牌排行"+"<br/>"
				+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"<br/>"
				+"场所名称："+siteIdForJituan+"<br/>"
				+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
			$("#paihangshuomingAll").html(biaogeshuomingContext);
	}
	
	
	
	var zlable = new Array();
	var zlable1 = new Array();
	var zdataPer = new Array();
	var zdata = new Array();
	if(orderBy=="1"){//1升序
		var index = rankingIndex;
		var indexName = getOrderField(index);
		var dataPer = new Array();
		var data = new Array();
		var lable = new Array();
		var lable1 = new Array();
		var max = getFildeMaxValue(parseDate,indexName);
		for(var i = 0; i < parseDate.length; i++){
			var datei = getObjectVlue(parseDate[i],indexName);
			data.push(datei);
			lable.push(parseDate[i].brandName);
			lable1.push(parseInt(i)+1);
			var dataPeri = 0;
			if(max==""||max=="0"){
				dataPeri = 0;
			}else{
				dataPeri = parseInt(datei)/parseInt(max)*100*7/10;
			}
			dataPer.push(dataPeri);
		}
		zlable = lable;
		zlable1 = lable1;
		zdataPer.push(dataPer);
		zdata.push(data);
	}else{//0降序
		var index = rankingIndex;
		var indexName = getOrderField(index);
		var dataPer = new Array();
		var data = new Array();
		var lable = new Array();
		var lable1 = new Array();
		var max =  getFildeMaxValue(parseDate,indexName);
		for(var i = 0; i < parseDate.length; i++){
			var datei = getObjectVlue(parseDate[i],indexName);
			data.push(datei);
			lable.push(parseDate[i].brandName);
			lable1.push(parseInt(i)+1);
			var dataPeri = 0;
			if(max==""||max=="0"){
				dataPeri = 0;
			}else{
				dataPeri = parseInt(datei)/parseInt(max)*100*7/10;
			}
			dataPer.push(dataPeri);
			
		}
		zlable = lable;
		zlable1 = lable1;
		zdataPer.push(dataPer);
		zdata.push(data);
		lable1.reverse();
	}
	loadPaihangbang(zdata,zlable,modolType,zdataPer,zlable1,rankingIndex,myChart);
}

function loadPaihangbang(data1,lable,modolType,zdataPer,lable1,rankingIndex,myCharttemp){
	var myChart = myCharttemp;
	var data1 = eval(data1);
	var zdataPer = eval(zdataPer);
	var legendDate = new Array();
	var num =zdataPer[0].length;
	var datatemp = "";
	for(var temp=0;temp<zdataPer.length;temp++){
		var data = data1[temp];
		var dataper= zdataPer[temp]
		var paihaindex = rankingIndex[temp];
		//获取指标名称
	     var paihaIndexname = array[parseInt(paihaindex)];
		 //获取指标单位
		 var paihaZhibiaodanwei = arraydanwei[parseInt(paihaindex)];
		var values = ""; 
		for(var dp = 0;dp <data.length;dp++ ){
			values = values+"{value: "+dataper[dp]+",tooltip : {show : true,backgroundColor: 'rgba(0,0,0,0.7)',position: function(p) {return [p[0] + 10, p[1] - 10];},formatter: '"+paihaIndexname+"("+paihaZhibiaodanwei+"):"+addKannma(data[dp])+"' }},";
		}
		datatemp = datatemp + "{barMaxWidth:20, barGap:'0%',barCategoryGap:10,name:'"+array[rankingIndex[temp]]+"',type:'bar',data: ["+values+"]},";
		legendDate.push(array[rankingIndex[temp]]);
	}
	datatemp = datatemp.substring(0,datatemp.length - 1);
	datatemp = eval("["+datatemp+"]");
	var paihangwidth = $("#divpaiming"+modolType).width();
	var paihangheight = $("#divpaiming"+modolType).height();
	var lable = eval(lable);
	
//	var xAxisMax = maxDate;
	var dataZoomEnd = 0;
	var dataZoomshow = true;//是否显示数据区域，如果小于等于7就不显示
	
	if( parseInt(num)<=7){
		dataZoomshow = false;
		dataZoomEnd=0;
	}else{
		dataZoomEnd =100-(100*7/num);
	}
	dataZoomX = paihangwidth*95.73/100;
	
	if( parseInt(num)<=7){
	var Y = 100- num*(90/7);
	var gridY = Y+'%';
	}else{
		gridY = "10%";
	}
	dataZoomHeight = paihangheight*94.7/100;
	option = {
	    calculable : false,
	    dataZoom : {
	      	orient:"horizontal",//horizontal,vertical
	        show : dataZoomshow,
	        realtime : true,
	        showDetail:false,
	        start : dataZoomEnd,
	        end : 100,
	        zoomLock:true,
	    },
	    tooltip : {
//	    	 trigger: 'item',
	    },
	    legend: {
	    	x: '5.3%',
			y: '0%',
	        data:legendDate
	    },
	    grid: {
			x: '5.3%',
	    	y:'5%',
	    	y2:gridY,
	    	x2: '10%',
			borderWidth: gridBorderWidth,
			borderColor:'#EEE'
		},
	   yAxis : [
	        {
				 splitLine: {show: yAxisSplitLine,
					lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
		        splitArea:{
					show:yAxissplitArea,
					areaStyle:{
								color: [
						        'rgba(250,250,250,0.1)',
						        'rgba(200,200,200,0.1)']
							}
				},
	            type : 'category',
	            boundaryGap : true,
	        	splitLine:{
	        		show:false
	            },
	          	axisLabel :{
	        		show:true
	            },
	            axisTick:{
        			show:false
	        	},
				axisLine :{
	        		show:false
	        	},
	            data : lable1
	        },
	     {
	            type : 'category',
	            axisLine :{
	        		show:false
	        	},
	        	splitLine:{
	        		show:false
	            },
	            axisTick:{
        			show:false
	        	},
	        	axisLabel:{
	        		textStyle:{
	        		align:'right',
					
	        	},
	        		margin:-10,
	        		
	        	},
	            boundaryGap : true,
	            data : lable
	        }
	    ],
	    xAxis : [
	        {
				 splitLine: {show: xAxisSplitLine,
					lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
	            splitArea:{
					show:xAxissplitArea,
					areaStyle:{
							color: [
					        'rgba(250,250,250,0.1)',
					        'rgba(200,200,200,0.1)']
						}
				},
	        	axisLabel :{
        			show:false
	        	},
	        	axisTick:{
        			show:false
	        	},
	        	axisLine :{
        			show:false
        		},
	            type : 'value',
	            min:0, 
	            max:100
	        }
	    ],
	    series : datatemp
	};
	
	//改变窗口大小使图标自适应窗口显示
		window.onresize = function () {
			myChart.resize();
		}
		//加载折线图
		option.animation = true;
		myChart.setOption(option);
}



//加载排行榜
 function loadSelectedRanking(type) {
 	var from = $('#startDate').val();
 	var to = $('#endDate').val();
 	var span = $("#txtspan").val();
 	var brandId = $("#brandIds").val();
 	$.ajax({
 		url: "getSelectedBrandRanking",
 		data: {type: type , from: from, to: to,span:span,brandId :brandId},
 		async: true,
 		success: function (result) {
 			var ret="";
 			ret=result.result;
 			$("#selectedRanking").html(ret);
 		}
 		}
 	);
 }
//加载排行榜
/**
 function loadPaiHang(type) {
 	var from = $('#startDate').val();
 	var to = $('#endDate').val();
 	var span = $("#txtspan").val();
 	$.ajax({
 		url: "getBrandRanking",
 		data: {type: type , from: from, to: to,span:span},
 		async: true,
 		success: function (result) {
 			var ret="";
 			ret=result.result;
 			$("#paihang").html(ret);
 		}
 		}
 	);
 }
*/

//加载图表
 function loadTable1(result) {
             $("#hdtable").val(result);
			 /**
			  * 测试
			  */
			 $("#datatable").html(result);
			showtable(1);
 }
